package gs.eisenhower.swallet.ui_component;

import gs.eisenhower.swallet.R;
import gs.eisenhower.swallet.dao.BudgetDao;
import gs.eisenhower.swallet.dao.BudgetDaoImpl;
import gs.eisenhower.swallet.dao.CategoryDao;
import gs.eisenhower.swallet.dao.CategoryDaoImpl;
import gs.eisenhower.swallet.model.Budget;
import gs.eisenhower.swallet.model.Category;
import gs.eisenhower.swallet.model.Wallet;
import gs.eisenhower.swallet.utility.FinanceType;
import gs.eisenhower.swallet.utils.constants.WalletConstants;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class EarningsFragment extends Fragment {
	private CategoryDao categoryTransaction;
	private BudgetDao budgetTransaction;
	private double budgetAmount;
	private List<String> categories;
	private ArrayAdapter<String> adapter;
	private final int requestedCode = 1;
	
	 @Override
	 public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                             Bundle savedInstanceState) {
	        return inflater.inflate(R.layout.fragment_earnings, container, false);
	 }
	 
	@Override
	public void onActivityCreated (Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		categoryTransaction = new CategoryDaoImpl();
		budgetTransaction   = new BudgetDaoImpl();
	
		updateSpinnerData();
		double budgetAmountLeft = budgetTransaction.read();
		updateBudgetAmountTextView(budgetAmountLeft);
		
		Button addTransactionButton = (Button) getView().findViewById(
				R.id.addTransactionButton);
		addTransactionButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (noNewAmount()) {
					return;
				}		
				double newAmount = getNewAmount();
				double actualAmount = budgetAmount + newAmount;
	
				addNewEarning(newAmount);
				refreshBudgetAmount(actualAmount);
				
				resetAllFields();
				updateBudgetAmountTextView(actualAmount);
				
				String title = "New Earning";
				String message = newAmount + WalletConstants.SPACE + WalletConstants.CURRENCY_CODE + " were added";
				showAlertDialog(title, message);
			}
		});
		
		Button editCategoriesButton = (Button) getView().findViewById(
				R.id.editButton);
		editCategoriesButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getView().getContext(), CategoryListView.class);
				intent.putStringArrayListExtra("Categories", (ArrayList<String>) categories);
				intent.putExtra("Entity", FinanceType.Earning.name());
				startActivityForResult(intent, requestedCode);
			}
		});
	}
	
	private void addNewEarning(double newAmount) {	
		Wallet newEarning = new Wallet();			
		newEarning.setCategory(getCategory());
		newEarning.setDetails(getDetails());
		newEarning.setAmount(newAmount);
		newEarning.setType(FinanceType.Earning.name());
		categoryTransaction.create(newEarning);
	}
	
	private void refreshBudgetAmount(double actualAmount) {
	    Date now = new Date();
	    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy");
	    SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm:ss");
	    
	    StringBuilder dateStringBuilder = new StringBuilder();
	    dateStringBuilder.append(timeFormatter.format(now));
	    dateStringBuilder.append(WalletConstants.SPACE);
	    dateStringBuilder.append(dateFormatter.format(now));
	   
		Budget updatedBudget = new Budget();
		updatedBudget.setAmount(actualAmount);
		updatedBudget.setTransactionDate(dateStringBuilder.toString());
		budgetTransaction.create(updatedBudget);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)  {
		if (requestCode == requestedCode) {
			List<String> updatedCategoryList = new ArrayList<String>(data.getStringArrayListExtra("Categories"));
			categories.clear();
			categories.addAll(updatedCategoryList);
			adapter.notifyDataSetChanged();
		}
	}
	
	private void updateBudgetAmountTextView(double amount) {
		budgetAmount = amount;
		TextView textView = (TextView) getView().findViewById(R.id.budgetTextView);
		String localeValue = NumberFormat.getInstance().format(amount);
		String text = "Current Budget: " + localeValue + WalletConstants.SPACE
				+ WalletConstants.CURRENCY_CODE;
		textView.setText(text);
	}

	private String getDetails() {
		EditText editText = (EditText) getView().findViewById(R.id.detailsEditText);
		return editText.getText().toString();
	}

	private String getCategory() {
		Spinner spinner = (Spinner) getView().findViewById(R.id.categorySpinnerEarning);
		return spinner.getSelectedItem().toString();
	}

	private double getNewAmount() {
		EditText editText = (EditText) getView().findViewById(R.id.newAmountEditText);
		double newAmount = Double.parseDouble(editText.getText().toString());
		return newAmount;
	}
	
	private void updateSpinnerData() {
		Spinner spinner = (Spinner) getView().findViewById(R.id.categorySpinnerEarning);
		Category category = new Category();
		category.setType(FinanceType.Earning.name());
		categories = categoryTransaction.read(category);
		adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
				R.layout.spinner_item, categories);
		spinner.setAdapter(adapter);
	}
	
	private void resetAllFields() {
		EditText editText1 = (EditText) getView().findViewById(R.id.newAmountEditText);
		editText1.setText("");
		
		Spinner spinner = (Spinner) getView().findViewById(R.id.categorySpinnerEarning);
		spinner.setSelection(0);
		
		EditText editText2 = (EditText) getView().findViewById(R.id.detailsEditText);
		editText2.setText("");
	}
	
	private boolean noNewAmount() {
		EditText editText = (EditText) getView().findViewById(R.id.newAmountEditText);
		if (editText.getText().toString().equals("")) {
			String title = "No new amount";
			String message = "Type amount to perform a new transaction";
			showAlertDialog(title, message);
			return true;
		} else {
			return false;	
		}
	}
	
	private void showAlertDialog(String title, String message) {		
		AlertDialog.Builder alertDialogBuilder = 
			new AlertDialog.Builder(getView().getContext());
		
		alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage(message);
		alertDialogBuilder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}
